// 定义请求路径, BASEURL: 普通请求API; CBASEURL: 中台API,不使用中台可不引入CBASEURL
const {
  baseUrl
} = require('./env')
const noNeedTokenApi = [
  'admin-api/system/auth/login'
]
// 定义默认参数
// const defaultOptions = {
//   data: {},
//   ignoreToken: false,
//   form: false,
// }
/**
 * 发送请求
 * @params
 * method: <String> 请求方式: POST/GET
 * url: <String> 请求路径
 * data: <Object> 请求参数
 * ignoreToken: <Boolean> 是否忽略token验证
 * form: <Boolean> 是否使用formData请求
 */
function request(url, data, options) {
  const defaultOptions = {
    data: {},
    ignoreToken: false,
    form: false,
  }
  let _options = Object.assign(defaultOptions, options)
  let {
    method,
    ignoreToken,
    form
  } = _options
  const app = getApp()
  // 设置请求头
  let header = {}
  if (form) {
    header = {
      'content-type': 'application/x-www-form-urlencoded'
    }
  } else {
    header = {
      'content-type': 'application/json' //自定义请求头信息
    }
  }
  if (!ignoreToken) {
    // 从全局变量中获取token
    let token = wx.getStorageSync('token')
    if(noNeedTokenApi.includes(url)){
      header.Authorization = ``
    }else{
      header.Authorization = `Bearer ${token}`
    }
    
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      data: { ...data, openId: wx.getStorageSync('openid') },
      header,
      method,
      success: (res) => {
        let {
          data,
          statusCode
        } = res
        if (statusCode !== 200) {
          showToast(`服务器异常`)
          reject(data)
        }
        if (data.code == 401) {
          wx.removeStorageSync('token')
          wx.removeStorageSync('userInfo')
          refreshFn()
          // refreshFn(method,()=>{
          //   request(url, {}, options)
          // })
          reject(data)
          return
        }
        if (data.code !== 0) {
          // 统一处理请求错误
          showToast(data.msg)
          reject(data)
        }
        resolve(data)
      },
      fail: (err) => {
        showToast(err.errMsg)
        reject(err)
      }
    })
  })
}

// 封装toast函数
function showToast(title, icon = 'none', duration = 2500, mask = false) {
  wx.showToast({
    title: title || '',
    icon,
    duration,
    mask
  });
}

function get(url, params, options) {
  return request(url, params, {
    method: 'GET',
    ...options
  })
}

function post(url, data, options) {
  return request(url, data, {
    method: 'POST',
    ...options
  })
}

function put(url, data, options) {
  return request(url, data, {
    method: 'PUT',
    ...options
  })
}
function del(url, data, options) {
  return request(url, data, {
    method: 'DELETE',
    ...options
  })
}

function uploadFile(filePath, type) {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      filePath: filePath,
      name: 'file',
      url: baseUrl + 'admin-api/infra/file/common-single-upload',
      // formData: {
      //   type: `xswl/${type}`
      // },
      success: res => {
        let {
          data,
          statusCode
        } = res
        data = JSON.parse(data)
        if (data.code != 0) {
          showToast(data.msg)
          reject(data.msg)
          return
        }
        resolve(data)
      },
      fail: (err) => {
        showToast('服务器异常')
        reject(err)
      }
    })
  })
}

function login(method, callback) {
  wx.login({
    success: async (result) => {
      const {
        data
      } = await post('wxlogin', {
        code: result.code
      })
      wx.setStorageSync('openid', data.loginBody.openId)
      wx.setStorageSync('token', data.token)
      const res = await get('wechatUser/getUserByOpenid')
      app.globalData.userInfo = res.data
      wx.setStorageSync('userInfo', res.data)
      if (method == 'GET' || method == 'get') {
        callback&&callback()
      }
    },
  })
}

function refreshFn(method, callback){
  wx.switchTab({
    url: '/pages/myInfo/myInfo',
  })
  showToast('登录已过期，请重新操作')
  return
  console.log("1111111http",wx.getStorageSync('refreshToken'))
  if(!wx.getStorageSync('refreshToken')){
    showToast('登录信息过期，请重新操作!')
    wx.reLaunch({
      url: '/pages/myInfo/myInfo'
    })
    return 
  }
  post(
    'admin-api/system/auth/refresh-token',
    {'refreshToken':wx.getStorageSync('refreshToken')},
    {'form':true}
  ).then(res=>{
    wx.setStorageSync('token', res.data.accessToken)
    wx.setStorageSync('refreshToken', res.data.refreshToken)
    const pages = getCurrentPages()
    const curpage = pages[pages.length - 1]
    wx.redirectTo({
      url: '/' + curpage.router,
    })
    console.log(pages,curpage,)
    console.log(method)
    if (method == 'GET' || method == 'get') {
      callback&&callback()
      curpage.onLoad()
    }
  })
  // .catch((err)=>{
  //   console.log("111111")
  //   debugger
  //   if(err){
  //     showToast('登录信息过期，请重新操作!')
  //     wx.redirectTo({
  //       url: '/pages/login/login'
  //     })
  //   }
  // })
}

module.exports = {
  request,
  get,
  post,
  put,
  del, 
  uploadFile
}